package binding

import (
	"encoding/json"
	"errors"
	"net/http"
)

var (
	EnableDecoderUserNumber           = false // 防止浮点数据精度丢失
	EnableDecoderDisableUnknownFields = false // 是否忽略无法匹配的字段
)

type JsonBind struct{}

func (j *JsonBind) Name() string {
	return "json"
}

func (j *JsonBind) Bind(req *http.Request, obj any) error {
	if req == nil || req.Body == nil {
		return errors.New("invalid request")
	}
	decoder := json.NewDecoder(req.Body)
	if EnableDecoderUserNumber {
		decoder.UseNumber()
	}
	if EnableDecoderDisableUnknownFields {
		decoder.DisallowUnknownFields()
	}
	if err := decoder.Decode(obj); err != nil {
		return err
	}
	return validate(obj)
}
